<?php
namespace App\Console\Commands;

use App\Services\Common\BaseService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class CreateDictionaryCommand extends Command
{
    protected $signature = 'create:dictionary';

    use CommandTrait;

    public function handle() {
        $this->createDictionary();
    }



    /**
     * 生成数据字典
     * @return false|int
     * @name:createDictionary
     * @author: lisa
     * @datetime: 2021/12/24 13:25
     */
    public function createDictionary() {
        $tables = Schema::getAllTables();
        $data = [];
        $str = "<?php \nreturn [\n";
        $database = env('DB_DATABASE');
        $database = "Tables_in_{$database}";
        foreach ($tables as $table) {
            $table_name = $table->{$database};
            $columns = DB::select('SHOW FULL COLUMNS FROM `' . $table_name . '`');
            foreach ($columns as $column) {
                \Log::info(json_encode($column, JSON_UNESCAPED_UNICODE));
                $type = $column->Type;
                $field = $column->Field;
                $isString = $this->isString($type);
                $isInteger = $this->isInteger($type);
                $isTinyint = $this->isTinyint($type);
                $isNumber = $this->isNumber($type);
                $isDate = $this->isDate($type);
                $isDateTime = $this->isDateTime($type);
                $isAmount = $this->isAmount($field);
                $ftype = '';
                if ($isString) $ftype = 'string';
                else if ($isAmount) $ftype = 'number';
                else if ($isInteger) $ftype = 'integer';
                else if ($isNumber) $ftype = 'number';
                else if ($isDateTime) $ftype = 'datetime';
                else if ($isDate) $ftype = 'date';
                if ($isTinyint) $ftype = 'boolean';
                $data[$table_name][$column->Field] = ['type' => $ftype, 'desc' => $column->Comment];
            }
        }
        foreach ($data as $k => $v) {
            $str .= "'{$k}' => [\n ";
            foreach ($v as $kk => $vv) {
                $str .= "'{$kk}' => ['type' => '{$vv['type']}', 'desc' => '{$vv['desc']}'],\n ";
            }
            $str .= " ],\n ";
        }
        $str .= '];';
        $config_path = config_path('dictionary.php');
        return file_put_contents($config_path, $str);
    }
}
